package com.houzehui.user.utils;

import com.houzehui.user.config.WebUtils;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;

@Slf4j
@Data
@Component
public class JwtUtils {

    private String secret = "bawei";

    private Integer expirationTime = 1000*3600*12;

    // 外部http请求中 header中 token的 键值
    private String header = "token";

    private static Map<String, String> tokenMap = new HashMap<>();

    /**
     * 生成token,加密用户信息
     * @param subject
     * @return
     */
    public String createToken(String subject) {
        Date nowDate = new Date();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(nowDate);
        calendar.add(Calendar.MINUTE, expirationTime);
        Date expireDate = calendar.getTime();

        String userToken = Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(subject)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
        // 把token添加到缓存中
        tokenMap.put(subject, userToken);
        return userToken;
    }

    public String createRefreshToken(String subject) {
        Date nowDate = new Date();
        return Jwts.builder()
                .setHeaderParam("typ", "JWT")
                .setSubject(subject)
                .setIssuedAt(nowDate)
                .signWith(SignatureAlgorithm.HS512, secret)
                .compact();
    }
    /**
     * 获取token中信息
     * @return
     */
    public String getUserInfo() {
        String token = WebUtils.getRequest().getHeader("token");
        Claims tokenClaim = getTokenClaim(token);
        //token过期情况
        if (tokenClaim==null){
            return null;
        }
        return tokenClaim.getSubject();
    }

    /**
     * 获取token中注册信息：解密用户信息
     * @param token
     * @return
     */
    public Claims getTokenClaim(String token) {
        if (token == null) {
            return null;
        }
        try {
            return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
        } catch (Exception e) {
            e.printStackTrace();
            //登陆过期，或token错误
            return null;
        }
    }

    /**
     * 验证token是否过期失效
     *
     * @param expirationTime
     * @return
     */
    public boolean isTokenExpired(Date expirationTime) {
        return expirationTime.before(new Date());
    }

    /**
     * 获取token失效时间
     *
     * @param token
     * @return
     */
    public Date getExpirationDateFromToken(String token) {
        return getTokenClaim(token).getExpiration();
    }


    /**
     * 获取jwt发布时间
     */
    public Date getIssuedAtDateFromToken(String token) {
        return getTokenClaim(token).getIssuedAt();
    }


    public static void main(String[] args) {
        JwtUtils jwtUtils = new JwtUtils();
        String token = jwtUtils.createToken("zhanggm");
        System.out.println(token);

        Claims tokenClaim = jwtUtils.getTokenClaim(token);
        System.out.println(tokenClaim.getSubject());
    }

}

